package com.easy.controller;

import com.easy.bean.CommentBean;
import com.easy.mapper.CommentDao;
import com.easy.service.CommentService;
import com.easy.service.impl.CommentServiceImpl;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private CommentDao commentDao;
//    @Autowired
//    private MessageService messageService;

    @PostMapping
    public Result addComment(@RequestBody CommentBean comment) {
        try {
            // 添加一些日志输出以便调试
            System.out.println("接收到的评论数据: " + comment);

            CommentBean savedComment = commentService.add(comment);
            return Result.success(savedComment);
        } catch (IllegalArgumentException e) {
            return Result.fail(400, e.getMessage()); // 改为 fail 方法
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "服务器内部错误");
        }
    }


    @DeleteMapping("{id}")
    public Result deleteComment(@PathVariable("id") Integer id) {
        try {
            int result = commentService.del(id);
            return result > 0 ? Result.success("删除成功") : Result.success("删除失败");
        } catch (IllegalArgumentException e) {
            return Result.success( e.getMessage());
        }
    }

    @GetMapping("/post/{postId}")
    public Result getCommentsByPost(@PathVariable("postId") Integer postId) {
        try {
//            CommentBean query = new CommentBean();
//            query = commentDao.all(postId);
//            System.out.println(query);
            List<CommentBean> comments = commentDao.all(postId);
            return Result.success(comments);
        } catch (Exception e) {
            // 添加详细错误日志
            e.printStackTrace();
            return Result.fail(500, "获取评论失败: " + e.getMessage());
        }
    }
    @GetMapping("/count/{postId}")
    public Result getCommentCount(@PathVariable("postId") Integer postId) {
        try {
            CommentBean query = new CommentBean();
            query.setPostId(postId);
            int count = commentService.countByPostId(query);
            return Result.success(count);
        } catch (IllegalArgumentException e) {
            return Result.success( e.getMessage());
        }
    }
}